<template>
    <div style="background-color: #EDEDED;" class="container " ref="contentRef" @scroll="handleScroll">
        <div class="top_bar">
            <!-- 总计标题 -->
            <div class="total_title"
                :style="{ transform: `translate(${options.titleTranslateX}rem, ${options.titleTranslateY}rem)` }">总金额
            </div>
            <!-- 总金额数值 -->
            <div class="total_money" ref="moneyRef"
                :style="{ transform: `translate(${options.moneyTranslateX}rem, ${options.moneyTranslateY}rem)` }">{{
                    formatMoneyNum(totalAccount) }}</div>
            <!-- <div class="total_money" ref="moneyRef"
                :style="{ transform: `translate(${options.moneyTranslateX}rem, ${options.moneyTranslateY}rem)` }">
                982000.99 </div> -->
        </div>
        <!-- 银行卡面板 -->
        <div class="card_panel" :style="{ overflow: options.parentScroll ? 'scroll' : 'hidden', }">
            <div class="card_panel_content">
                <MyCardList :cardList="cardList" />
            </div>
        </div>
        <LayoutIndex />
        <!-- 添加账户按钮 -->
        <van-floating-bubble axis="xy" style="z-index: 99;" v-model:offset="offset" v-if="!showDia"
            icon="cash-back-record-o" magnetic="x" @click="showDia = true" />
        <van-popup v-model:show="showDia" position="bottom" :style="{ padding: '15px', height: '60%' }" round>
            <AddCardVue v-if="showDia" @successAdd="successAdd" />
        </van-popup>
        <!-- 遮罩层 -->
        <van-overlay :show="loading" z-index="10000">
            <div class="wrapper" @click.stop>
                <van-loading size="30px" vertical color="#0094ff">加载中...</van-loading>
            </div>
        </van-overlay>
    </div>
</template>

<script setup>
import { ref, onUnmounted, reactive, onMounted, computed } from "vue"
import LayoutIndex from "./layout/Index.vue"
import AddCardVue from '@/views/account/AddCardVue.vue'
import MyCardList from "./MyCardList.vue";
// queryCardList
import { queryCardList } from "@/api/index"
import { showToast } from "vant";
// 浮动气泡的位置
const offset = ref({ x: '9rem', y: 700 })

const showDia = ref(false)
const successAdd = () => {
    showDia.value = false
    // 获取银行卡列表
    queryCardList_()
}


const moneyRef = ref(null)
const intervalId = ref(null)
// 格式化钱
const formatMoneyNum = (num) => {

    const options = {
        style: 'currency',
        currency: 'CNY',
    };
    return num.toLocaleString("zh-CN", options);
}
// 格式化钱的另一种方式
function formatMoney(num) {
    return num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
// 更新金额的函数，包含滚动动画  
const updateMoney = (oldVal, newVal) => {
    // 初始化当前值  
    let currentValue = parseInt(oldVal, 10);
    // 创建定时器，逐步增加或减少金额  
    intervalId.value = setInterval(() => {
        if (currentValue !== newVal) {
            const type = Math.sign(newVal - currentValue); // 根据方向增加或减少1  
            // 生成一个当前值与最终值之间的随机数
            const randomNum = Math.floor(Math.random() * Math.abs(newVal - currentValue));
            if (type === 1) {
                currentValue += randomNum;
            } else {
                currentValue -= randomNum;
            }
            const options = {
                style: 'currency',
                currency: 'CNY',
            };
            moneyRef.value.textContent = currentValue.toLocaleString("zh-CN", options); // 格式化为带千位分隔符的数字  
        } else {
            clearInterval(intervalId.value); // 达到目标值后停止定时器  
        }
    }, 10); // 每10毫秒更新一次金额  
};

// 标题结果距离     transform: translate(-4.2rem, 0.47rem);
// 金额结果距离     transform: translate(0rem, -0.4rem);
const options = reactive({
    // 标题移动的Y距离
    titleTranslateY: 1.9231,
    // 标题移动的x距离
    titleTranslateX: 0,
    // 总金额数值移动的Y距离
    moneyTranslateY: 1.9231,
    // 总金额数值移动的x距离
    moneyTranslateX: 0,
    // 父级盒子是否滚动
    parentScroll: false,
    // 父级盒子滚动距离
    parentScrollDistance: 0,
    // 上一次的滚动距离
    lastScrollTop: 0,
})

// 计算金额的滚动距离
const calculateMoneyScrollDistance = (scrollTop, type) => {
    // type 1为向下滚动，2为向上滚动  上下指的是鼠标滚轮
    //计算滚动距离比例
    const scrollDistanceRatio = (6.55 / 145).toFixed(2)
    // 计算滚动距离
    const scrollDistance = scrollTop * scrollDistanceRatio
    // console.log("金额滚动距离:", scrollDistance);
    // 更新金额的滚动距离
    type == 1 ? options.moneyTranslateY -= pxToRem(scrollDistance) : options.moneyTranslateY += pxToRem(scrollDistance)
    // 更新标题的滚动距离
}

const contentRef = ref(null);
const handleScroll = () => {
    const scrollTop = contentRef.value.scrollTop;
    // console.log("滚动高度:", scrollTop);
    // scrollTop > options.lastScrollTop ? calculateMoneyScrollDistance(scrollTop, 1) : calculateMoneyScrollDistance(scrollTop, 2)
    // options.lastScrollTop = scrollTop;
    if (scrollTop < 123) {
        // 当滚动高度小于等于146px时，动态设置头部高度
        if (!options.parentScroll) {
            return
        }
        options.moneyTranslateY = 1.9231
        options.titleTranslateY = 1.9231
        options.titleTranslateX = 0
        options.parentScroll = false;

    } else {
        // 当滚动高度大于100px时，固定头部高度为100px
        if (options.parentScroll) {
            return
        }

        options.moneyTranslateY = -0.4
        options.titleTranslateY = 0.47
        options.titleTranslateX = -4.2
        options.parentScroll = true;
    }
}
// 将REM转换为PX
function remToPx(remValue) {
    // 获取当前文档的根元素的字体大小（即1REM的值）
    const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    // 将REM值乘以根元素的字体大小，得到相应的PX值
    return remValue * fontSize;
}

// 将PX转换为REM
function pxToRem(pxValue) {
    // 获取当前文档的根元素的字体大小（即1REM的值）
    const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    // 将PX值除以根元素的字体大小，得到相应的REM值
    return pxValue / fontSize;
}
const loading = ref(false)
const cardList = ref([])
// 查询卡列表
const queryCardList_ = async () => {
    loading.value = true
    const userInfo = localStorage.getItem("userInfo");
    const uid = JSON.parse(userInfo).id;
    const res = await queryCardList(uid)
    loading.value = false
    if (res.status == 200) {
        console.log("查询卡列表成功:", res.data);
        cardList.value = res.data
    }
    else {
        showToast({
            message: "查询卡列表失败",
            duration: 2000,
            forbidClick: true,
        })
    }
}
// 计算总金额
const totalAccount = computed(() => {

    return cardList.value.reduce((acc, cur) => acc + parseFloat(cur.current_amount), 0)
})
onMounted(() => {
    queryCardList_()
})
onUnmounted(() => {
    console.log("组件卸载了");
    clearInterval(intervalId.value); // 组件卸载时清除定时器
})
</script>

<style lang="scss" scoped>
.container {
    height: 100vh;
    overflow: scroll;
    position: relative;
    z-index: 99;

    .wrapper {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .top_bar {
        background: #1D2027 url("@/assets/Frame.png") no-repeat center center;
        background-size: 100% 100%;
        height: 10.6154rem;
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        z-index: -1;
        transition: all 0.3s ease;
        /* 添加动画效果 */

        .total_title {
            /* transform: translateY(1.9231rem); */
            text-align: center;
            font-size: .3077rem;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: .4615rem;
            color: rgb(168 172 37);
        }

        .total_money {
            /* transform: translateY(1.9231rem); */
            text-align: center;
            font-size: .9231rem;
            font-weight: 700;
            letter-spacing: 0px;
            line-height: 1.1538rem;
            color: rgba(255, 255, 255, 1);
            font-family: Arial, sans-serif;
            font-size: 18px;
            padding: 5px 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

    }

    .card_panel {
        background-color: #1D2027;
        transition: all 0.3s ease;
        height: calc(100vh - 1.3rem);
        transform: translateY(4.4462rem);
        /* transform: translateY(5.0462rem); */

        .card_panel_content {
            background-color: #fff;
            /* height: 29.88rem; */
            border-radius: .5128rem .5128rem 0 0;
            padding: .5128rem;
            margin-bottom: 1.2rem;

            .card_panel_content_item {
                height: 30px;
                background-color: aquamarine;
            }
        }
    }
}
</style>